//Blimps variables
	var CurrentAltitude;
	var AltitudeCommand;
	var CurrentSpeed;
	var SpeedCommand;
	var CurrentHeading;
	var TurnCommand;
	var Distance;
	var BlimpPositionsX = new Array();
	var BlimpPositionsY = new Array();
	BlimpPositionsX[0] = 250;
	BlimpPositionsY[0] = 200;
	
	//Tag Variables
	var Tag1;
	var Tag1IdDisp;
	var Tag1ID;
	var Tag1Xpos;
	var Tag1Ypos;
	var Tag1Angle;
	var Tag2;
	var Tag2IdDisp;
	var Tag2ID;
	var Tag2Xpos;
	var Tag2Ypos;
	var Tag2Angle;
	var Tag3;
	var Tag3IdDisp;
	var Tag3ID;
	var Tag3Xpos;
	var Tag3Ypos;
	var Tag3Angle;
	
	//Highchart object (real time graph)
	var TelemGraph;
	
	//Real time viewer variables
	var Canvas;
	var BaseStation;
	var Blimp;
	var BlimpShadow;
	var ShadowOffsetX;
	var ShadowOffsetY;
	var BlimpShadowScale;
	var BlimpShadowOpacity;
	var BlimpPath;
	
	//HTTP request objects and Command String
	var Request = new XMLHttpRequest();
	var TELEMRequest = new XMLHttpRequest();
	var QueuedCommands = "";
	var QueuedCommandsCount = 0;
	
	function startPeriodicUpdate() {
		setInterval("RequestTELEM();",1000); //4 second refresh
	}
	
	function AppendCommand (CMD) {
		if (QueuedCommandsCount < 20){
			if (CMD == "FBP") { QueuedCommands += 'f'; } //Forward
			else if (CMD == "BBP") { QueuedCommands += 'b'; } //Back
			else if (CMD == "LBP") { QueuedCommands += 'l'; } //Left
			else if (CMD == "RBP") { QueuedCommands += 'r'; } //Right
			else if (CMD == "UBP") { QueuedCommands += 'u'; } //Up
			else if (CMD == "DBP") { QueuedCommands += 'd'; } //Down
			else if (CMD == "KILL") { //Stop All (Kill System)
				QueuedCommands = 's'; 
				QueuedCommandsCount = 20;
			} 
			QueuedCommandsCount++;
			console.log(QueuedCommands,QueuedCommandsCount);
		}
	}
	
	function RequestTELEM() {
		if (TELEMRequest){
			TELEMRequest.onreadystatechange = UpdateScene; 
			Dest_URL = '/RFS/' + QueuedCommands + '/';
			TELEMRequest.open("GET", Dest_URL, true);
			TELEMRequest.send();
			QueuedCommands = "";
			QueuedCommandsCount = 0;
		}
	}
			
	function UpdateScene() {
		if (TELEMRequest.readyState == 4) { 
			// only if "OK" 
			if (TELEMRequest.status == 200) { 
				var rawData = TELEMRequest.responseText; 
				var dataArray = rawData.split('-');
				
				console.log("%s",rawData);
				
				CurrentAltitude = parseInt(dataArray[0] + "<br>");//Math.random()*255;
				AltitudeCommand = parseInt(dataArray[1] + "<br>");
				//CurrentSpeed = parseInt(dataArray[2] + "<br>");
				SpeedCommand = parseInt(dataArray[3] + "<br>");
				CurrentHeading = parseInt(dataArray[4] + "<br>");
				TurnCommand = parseInt(dataArray[5] + "<br>");
				Distance = parseInt(dataArray[6] + "<br>");
				Angle = parseInt(dataArray[7] + "<br>");
				Tag1ID = dataArray[8];
				Tag1Xpos = parseInt(dataArray[9] + "<br>");
				Tag1Ypos = parseInt(dataArray[10] + "<br>");
				Tag1Angle = parseInt(dataArray[11] + "<br>");
				Tag2ID = dataArray[12];
				Tag2Xpos = parseInt(dataArray[13] + "<br>");
				Tag2Ypos = parseInt(dataArray[14] + "<br>");
				Tag2Angle = parseInt(dataArray[15] + "<br>");
				Tag3ID = dataArray[16];
				Tag3Xpos = parseInt(dataArray[17] + "<br>");
				Tag3Ypos = parseInt(dataArray[18] + "<br>");
				Tag3Angle = parseInt(dataArray[19] + "<br>");
				
				if (isNaN(CurrentAltitude)) { (CurrentAltitude = null); }
				if (isNaN(AltitudeCommand)) { (AltitudeCommand = null); }
				if (isNaN(SpeedCommand)) { (SpeedCommand = null); }
				if (isNaN(CurrentHeading)) { (CurrentHeading = null); }
				if (isNaN(TurnCommand)) { (TurnCommand = null); }
				if (isNaN(Distance)) { (Distance = null); }
				if (isNaN(Angle)) { (Angle = null); }
				
				var BX = ((Distance) * Math.cos(Angle)) + 250;
				var BY = ((Distance) * Math.sin(Angle)) + 200;

				BlimpPositionsX.unshift(BX);
				BlimpPositionsY.unshift(BY);
				
				CurrentSpeed = Math.sqrt(Math.pow(BX-BlimpPositionsX[1],2) + Math.pow(BY-BlimpPositionsY[1],2));
				if (isNaN(CurrentSpeed)) { (CurrentSpeed = null); }
				
				document.getElementById("T_Altitude").innerHTML = CurrentAltitude; 
				document.getElementById("T_Heading").innerHTML = CurrentHeading; 
				document.getElementById("T_Speed").innerHTML = CurrentSpeed; 
				document.getElementById("T_TurnCMD").innerHTML = TurnCommand; 
				
				//console.log("%d | %d | %d | %d | %d | %d | %d | %d",CurrentAltitude,AltitudeCommand,CurrentSpeed,SpeedCommand,CurrentHeading,TurnCommand,Distance,Angle);
				
				Tag1.remove();
				Tag1Xpos = (480*(Tag1Xpos-50)/470)+10;
				Tag1Ypos = (380*(Tag1Ypos-40)/410)+10;
				Tag1 = Canvas.rect(Tag1Xpos,Tag1Ypos,20,20).attr({opacity : '0.5' , fill : '#00f'}); //(X,Y, sizeX, sizeY)
				Tag1.rotate(Tag1Angle * (180/Math.PI));
				Tag1IdDisp.remove();
				Tag1IdDisp = Canvas.text(Tag1Xpos+10,Tag1Ypos+10,Tag1ID).attr({ 'font-size': 12, fill: '#FFFFFF', cursor: 'pointer' });
				
				Tag2.remove();
				Tag2Xpos = (480*(Tag2Xpos-50)/470)+10;
				Tag2Ypos = (380*(Tag2Ypos-40)/410)+10;
				Tag2 = Canvas.rect(Tag2Xpos,Tag2Ypos,20,20).attr({opacity : '0.5' , fill : '#0f0'}); //(X,Y, sizeX, sizeY)
				Tag2.rotate(Tag2Angle * (180/Math.PI));
				Tag2IdDisp.remove();
				Tag2IdDisp = Canvas.text(Tag2Xpos+10,Tag2Ypos+10,'2').attr({ 'font-size': 12, fill: '#FFFFFF', cursor: 'pointer' });
				
				Tag3.remove();
				Tag3Xpos = (480*(Tag3Xpos-50)/470)+10;
				Tag3Ypos = (380*(Tag3Ypos-40)/410)+10;
				Tag3 = Canvas.rect(Tag3Xpos,Tag3Ypos,20,20).attr({opacity : '0.5' , fill : '#f00'}); //(X,Y, sizeX, sizeY)
				Tag3.rotate(Tag3Angle * (180/Math.PI));
				Tag3IdDisp.remove();
				Tag3IdDisp = Canvas.text(Tag3Xpos+10,Tag3Ypos+10,'3').attr({ 'font-size': 12, fill: '#FFFFFF', cursor: 'pointer' });
				
				Blimp.remove();
				var AltitudeScaler = ((0.7/300)*CurrentAltitude) + 1;
				Blimp = Canvas.ellipse(BX, BY, 20*AltitudeScaler, 10*AltitudeScaler);  
				Blimp.attr("fill", "#0f0");
				Blimp.rotate(CurrentHeading);
				
				BlimpShadow.remove();
				BlimpShadowScale = ((0.7/300)*CurrentAltitude) + 0.2;
				ShadowOffsetX = ((13/300)*CurrentAltitude) + 6;
				ShadowOffsetY = ((12/300)*CurrentAltitude) + 8;
				BlimpShadow = Canvas.ellipse(BX+ShadowOffsetX, BY+ShadowOffsetY, (20*BlimpShadowScale), (10*BlimpShadowScale));  
				BlimpShadowOpacity = ((0.7/300)*CurrentAltitude) + 0.2;
				BlimpShadow.attr('opacity', (1-BlimpShadowOpacity));
				BlimpShadow.attr("fill", "#000");
				BlimpShadow.toBack();
				BlimpShadow.rotate(CurrentHeading);
				
				BlimpPath.remove();
				BlimpPath = Canvas.path("M" + BlimpPositionsX[0] + " " + BlimpPositionsY[0] + " " +
										"l" + (BlimpPositionsX[1] - BlimpPositionsX[0]) + " " + (BlimpPositionsY[1] - BlimpPositionsY[0]) +
										"l" + (BlimpPositionsX[2] - BlimpPositionsX[1]) + " " + (BlimpPositionsY[2] - BlimpPositionsY[1]) +
										"l" + (BlimpPositionsX[3] - BlimpPositionsX[2]) + " " + (BlimpPositionsY[3] - BlimpPositionsY[2]) +
										"l" + (BlimpPositionsX[4] - BlimpPositionsX[3]) + " " + (BlimpPositionsY[4] - BlimpPositionsY[3]) +
										"l" + (BlimpPositionsX[5] - BlimpPositionsX[4]) + " " + (BlimpPositionsY[5] - BlimpPositionsY[4]) +
										"l" + (BlimpPositionsX[6] - BlimpPositionsX[5]) + " " + (BlimpPositionsY[6] - BlimpPositionsY[5]) +
										"l" + (BlimpPositionsX[7] - BlimpPositionsX[6]) + " " + (BlimpPositionsY[7] - BlimpPositionsY[6]) +
										+ "z");
				
				TelemGraph.get('AltitudeCMD').addPoint(CurrentAltitude, true, true);
				TelemGraph.get('Altitude').addPoint(AltitudeCommand, true, true);
				TelemGraph.get('Heading').addPoint(CurrentHeading, true, true);
				TelemGraph.get('HeadingCMD').addPoint(TurnCommand, true, true);
				TelemGraph.get('Distance').addPoint(Distance, true, true);
				TelemGraph.get('Speed').addPoint(CurrentSpeed, true, true);
				TelemGraph.get('SpeedCMD').addPoint(SpeedCommand, true, true);
			} else { 
				//alert("There was a problem retrieving the XML data:\n" + Request.statusText); 
				console.log("There was a problem retrieving the XML data:\n" + Request.statusText);
			} 
		} 
	}
	
	var options = {
		chart: {
			renderTo: 'Graph',
			type: 'line',
			animation: Highcharts.svg, // don't animate in old IE
			marginRight: 150,
		},
		title: {
			text: 'Telemetry data'
		},
		xAxis: {
			type: 'time',
			tickPixelInterval: 150
		},
		yAxis: {
			title: {
				text: 'Command Value'
			},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		},
		legend: {
			layout: 'vertical',
			align: 'right',
			verticalAlign: 'top',
			x: -10,
			y: 100,
			borderWidth: 1
		},
		exporting: {
			enabled: false
		},
		series: [{
			id: 'Altitude',
			name: 'Altitude',
			data: [0,0,0,0,0,0,0,0]
		//	data: JSON.parse("[" + CurrentAltitude + "]")
		}, {
			id: 'AltitudeCMD',
			name: 'Altitude CMD',
			data: [127,127,127,127,127,127,127,127]
		}, {
			id: 'Heading',
			name: 'Heading',
			data: [180,180,180,180,180,180,180,180]
		}, {
			id: 'HeadingCMD',
			name: 'Heading CMD',
			data: [127,127,127,127,127,127,127,127]
		}, {
			id: 'Distance',
			name: 'Distance',
			data: [0,0,0,0,0,0,0,0]
		}, {
			id: 'Speed',
			name: 'Speed',
			data: [0,0,0,0,0,0,0,0]
		}, {
			id: 'SpeedCMD',
			name: 'Speed CMD',
			data: [127,127,127,127,127,127,127,127]
		}]
	};

$(function () {
	TelemGraph = new Highcharts.Chart(options);
	startPeriodicUpdate();
})

window.onload = function() {  
    Canvas = new Raphael(document.getElementById('canvas'), 500, 400);  
	
	BaseStation = Canvas.circle(250, 200, 10);
	BaseStation.attr("fill", "#f00");
	BaseStation.attr("stroke", "#fff");
	
	Blimp = Canvas.ellipse(250, 200, 20, 10);  
	Blimp.attr("fill", "#0f0");
	Blimp.rotate(90);
	
	ShadowOffsetX = 5;
	ShadowOffsetY = 5;
	BlimpShadowOpacity = 0.9;
	BlimpShadow = Canvas.ellipse(250+ShadowOffsetX, 200+ShadowOffsetY, 20-2, 10-1);  
	BlimpShadow.attr('opacity', BlimpShadowOpacity);
	BlimpShadow.attr("fill", "#000");
	BlimpShadow.toBack();
	BlimpShadow.rotate(90);
	
	//BlimpPath = Canvas.path("M 250 250 l 0 -50 l -50 0 l 0 -50 l -50 0 l 0 50 l -50 0 l 0 50 z");
	//BlimpPath = Canvas.path("M" + BlimpPositionsX[0] + BlimpPositionsY[0] + "l 0 -50 l -50 0 l 0 -50 l -50 0 l 0 50 l -50 0 l 0 50 z");
	BlimpPath = Canvas.path("M 250 200");
	BlimpPath.animate({rotation: 360}, 2000, 'bounce'); 
	
	Tag1 = Canvas.rect(10,10,20,20).attr({opacity : '0.5' , fill : '#00f'}); //(X,Y, sizeX, sizeY)
	Tag1IdDisp = Canvas.text(10+10,10+10,'1').attr({ 'font-size': 12, fill: '#FFFFFF', cursor: 'pointer' });
	Tag2 = Canvas.rect(30,10,20,20).attr({opacity : '0.5' , fill : '#0f0'}); //(X,Y, sizeX, sizeY)
	Tag2IdDisp = Canvas.text(30+10,10+10,'2').attr({ 'font-size': 12, fill: '#FFFFFF', cursor: 'pointer' });
	Tag3 = Canvas.rect(50,10,20,20).attr({opacity : '0.5' , fill : '#f00'}); //(X,Y, sizeX, sizeY)
	Tag3IdDisp = Canvas.text(50+10,10+10,'3').attr({ 'font-size': 12, fill: '#FFFFFF', cursor: 'pointer' });
}
